package service;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;

import domain.RelatedFile;

/**
 * 负责管理已上传的文件列表的服务． 上传文件时，调用相关的方法完成文件的保存．
 * @author wuzh
 */
public class UploadedFileService {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger
            .getLogger(UploadedFileService.class);

    /** Hibernate SessionFactory. */
    private SessionFactory sessionFactory;

    /**
     * 添加上传文件的记录
     * @param uploadedFile 上传的文件信息.
     */
    public void addUploadedFileInfo(RelatedFile uploadedFile) {
        uploadedFile.setUploadedTime(new java.sql.Timestamp(System
                .currentTimeMillis()));
        sessionFactory.getCurrentSession().save(uploadedFile);
    }

    /**
     * 删除已上传的文件的记录(以及文件本身)
     * @param deleteFile 是否同时删除文件
     * @param uploadedFileID id
     */
    public void removeUploadedFileInfo(Integer uploadedFileID,
            boolean deleteFile) {
        RelatedFile fileInfo = (RelatedFile) sessionFactory
                .getCurrentSession().get(RelatedFile.class, uploadedFileID);
        if (fileInfo == null) {
            logger.warn("delete not found file ,id is " + uploadedFileID);
            return;
        }
        sessionFactory.getCurrentSession().delete(fileInfo);
        if (deleteFile) {
            try {
                FileUtils.forceDelete(new File(fileInfo.getFullName()));
            } catch (IOException e) {
                logger.warn("delete file err ", e);
            }
        }

    }

    /**
     * set sessionFactory
     * @param pSessionFactory sessionFactory
     */
    public void setSessionFactory(SessionFactory pSessionFactory) {
        sessionFactory = pSessionFactory;
    }
}
